require("../../both/base.js");

require("./DataTable.scss");

// todo : 不应该把Popup写在DataTable里面导致复用困难，包括函数名称应该都是addData而非addCourses
const majors = ["嵌入式","Web","Android","IOS","UI"]

// todo : 应该给datatable单独搞一个action和reducer

const PropTypes = React.PropTypes
// todo : 去除wrap函数，直接写在Container里面
class DataTable extends React.Component{
    constructor(props){
        super(props)
        this.sortFlag = 0       // 判定升序降序
        this.sortIdx = -1       // 记录当前排序的列下标
        this.page = 1
        this.limit = 10

        this.state = {
            modalState : false,
            title : "",
            description : "",
            major : majors[0],
            cover : `${location.protocol}//${location.hostname}:${location.port}/p_dist/default.jpg`,
            videoUrl : `${location.protocol}//${location.hostname}:${location.port}/p_dist/default.mp4`
        }
    }

    sortWrap(e){
        const {sort} = this.props
        if(typeof sort !== "function"){       // 如果没有sort属性
            return
        }

        var childrenArr = this.theads.children
        var idx
        for(var child of childrenArr){
            if(child.children[0].children[0].isEqualNode(e.target)){
                idx = Array.prototype.indexOf.call(childrenArr,child)
            }
        }
        if(typeof idx !== "undefined" && idx !== null){
            sort(idx,this.sortFlag)
            this.sortFlag = this.sortFlag ? 0 : 1

            this.changeSortAngle(idx)       // 改变箭头方向
        }
    }

    changeSortAngle(idx){
        let th = this.theads.children[idx]
        let angleArr = th.querySelectorAll("i.fa")

        if(this.sortIdx !== -1){  // 如果当前有排序，先清除
            let oldTh = this.theads.children[this.sortIdx]
            let oldAngleArr = oldTh.querySelectorAll("i.fa")
            oldAngleArr[0].style.display = "inline-block"
            oldAngleArr[1].style.display = "inline-block"
        }

        if(this.sortFlag){
            angleArr[0].style.display = "inline-block"
            angleArr[1].style.display = "none"
        }else{
            angleArr[0].style.display = "none"
            angleArr[1].style.display = "inline-block"
        }

        this.sortIdx = idx
    }

    searchWrap(){
        const {search} = this.props
        if(typeof search !== "function"){       // 如果没有sort属性
            return
        }

        search(this.searchInput.value)
    }

    showMore(){

    }

    /**
     * resize thead的宽度
     */
    resizeColGroup(){
        let ths = Array.from(this.theads.children)
        let cols = Array.from(this.colgroup.children)
        for(let child of ths){
            cols[ths.indexOf(child)].style.width = window.getComputedStyle(child)["width"]
        }

        // hack由于滚动条出现导致的偏移
        let scrollWidth = 17
        let tbodyHeight = parseInt(window.getComputedStyle(this.tbody,null)["height"].replace(/px/gi,""))
        if(tbodyHeight >= 600){
            document.getElementById("head_wrap").style.paddingRight = scrollWidth + "px"
        }else{
            document.getElementById("head_wrap").style.paddingRight = 0 + "px"
        }
    }

    componentDidUpdate(){
        const resizeColGroup = this.resizeColGroup.bind(this)
        resizeColGroup()
    }

    componentDidMount(){
        const resizeColGroup = this.resizeColGroup.bind(this)
        resizeColGroup()
    }

    changePageWrap(page){
        var self = this
        return function(e){
            var regx = new RegExp("disable")
            if(e && (regx.test(e.target.className) || (regx.test(e.target.parentNode.className))) ){
                return
            }

            const {changePage,totalCount} = self.props

            var limit = self.limit

            self.page = page || self.page
            var firstBtn = document.getElementsByClassName("first_page")[0]
            var lastBtn = document.getElementsByClassName("last_page")[0]
            var prevBtn = document.getElementsByClassName("prev_page")[0]
            var nextBtn = document.getElementsByClassName("next_page")[0]

            firstBtn.className = firstBtn.className.replace(/disable/gi,"")
            lastBtn.className = lastBtn.className.replace(/disable/gi,"")
            prevBtn.className = prevBtn.className.replace(/disable/gi,"")
            nextBtn.className = nextBtn.className.replace(/disable/gi,"")

            if(self.page === 1){
                firstBtn.className += " disable "
                prevBtn.className += " disable "
            }

            if(totalCount / limit - page <= 0){
                nextBtn.className += " disable "
                lastBtn.className += " disable "
            }

            changePage(self.page,limit)
        }
    }

    onLimitChange(){
        const { totalCount } = this.props
        var limitSelect = document.getElementById("limit")
        var limit = limitSelect.value
        limit = limit === "全部" ?  totalCount : limit
        this.limit = limit

        this.changePageWrap(1)()
    }

    selectCourseWrap(e){
        const { selectCourse, courses } = this.props
        var regx = new RegExp("^radio_input$","gi")     // span
        if(regx.test(e.target.className)){
            var span = e.target
            var courseId = span.dataset.id
            var course
            for(course of courses){
                if(course.id == courseId){
                    break
                }
            }
            selectCourse(course)
            var tr = span.parentNode.parentNode.parentNode.parentNode
            regx = new RegExp("selected","gi")
            if(regx.test(tr.className)){
                tr.className = tr.className.replace("selected","")
            }else{
                tr.className += " selected "
            }
        }
    }

    moveWrap(direction){
        var self = this
        return function(e){
            const { move,selectedCourses } = self.props
            e.preventDefault()
            if(selectedCourses.length !== 1){
                return
            }else{
                move(direction,selectedCourses[0])
            }
        }
    }

    /**
     * 这个函数是用来让父亲组件通过props控制，触发子组件的一些行为
     * @returns {XML}
     */
    // componentWillReceiveProps(nextProps){
    //     console.log(nextProps)
    // }

    // wrap 函数可以除去，应该使用componentWillReceiveProps来修改样式或者通过State来修改
    render(){
        var self = this
        const {refresh,courses,sort,search,changePage,totalCount,selectedCourses,move,addCourse} = self.props

        // wrap functions
        const sortWrap = this.sortWrap.bind(this)  // 排序功能包裹函数
        const searchWrap = this.searchWrap.bind(this) // 搜索功能包裹函数
        const showMore = this.showMore.bind(this)
        const changePageWrap = this.changePageWrap.bind(this)
        const onLimitChange = this.onLimitChange.bind(this)
        const selectCourseWrap = this.selectCourseWrap.bind(this)
        const moveWrap = this.moveWrap.bind(this)
        const showModal = this.props.showModal

        // DataTable复用
        const trs = this.props.trs

        return (
            <div className="datatable_container bln">
                <div className="table_ctrl">
                    <ul className="table_ctrl_operator">
                        <li><a href="javascript:void(0)"><div className={ this.props.addDisable ? "default disable" : "default"} onClick={showModal}><i className="fa fa-plus"></i>&nbsp;添加</div></a></li>
                        <li><a href="javascript:void(0)" onClick={moveWrap("up")}><div className={selectedCourses.length !== 1 ? "disable" : "op" }>上移</div></a></li>
                        <li><a href="javascript:void(0)" onClick={moveWrap("down")}><div className={selectedCourses.length !== 1 ? "disable" : "op" }>下移</div></a></li>
                        <li>
                            <a href={selectedCourses.length !== 1 || this.props.editDisable ? "javascript:void(0)" : this.props.editHref + selectedCourses[0].id }>
                                <div className={selectedCourses.length !== 1 || this.props.editDisable ? "disable" : "op"}>修改
                                </div>
                            </a>
                        </li>
                        <li>
                            <a href="javascript:void(0)">
                                <div className="more" onClick={showMore}>更多操作&nbsp;<i className="fa fa-angle-down"></i>
                                </div>
                            </a>
                        </li>
                    </ul>
                    <ul className="table_ctrl_operator_fr">
                        {
                            search ?
                            <li>
                                <div className="input_wr">
                                    <input type="text" placeholder={this.props.searchPlaceHolder} ref={(node) => this.searchInput = node }
                                           onChange={searchWrap}/>
                                    <div className="operator_icon search_btn" onClick={searchWrap}><i
                                        className="fa fa-search"></i></div>
                                </div>
                            </li> : null
                        }
                        <li><a href="javascript:void(0)">
                            <div className="operator_icon" onClick={refresh}><i className="fa fa-refresh"></i></div>
                        </a></li>
                        {/*<li><a href="#">*/}
                            {/*<div className="operator_icon"><i className="fa fa-cog"></i></div>*/}
                        {/*</a></li>*/}
                        {/*<li><a href="#">*/}
                            {/*<div className="operator_icon"><i className="fa fa-download"></i></div>*/}
                        {/*</a></li>*/}
                    </ul>
                </div>
                <div className="datatable_cr">
                    <div className="head_wrap" id="head_wrap">
                    <table className="datatable">
                        <thead>
                        <tr ref={(node) => this.theads = node} onClick={sortWrap.bind(this)}>
                            {
                                this.props.selectDisable || <td>
                                    <div className="text-center">
                                        <label htmlFor="radio_input_select">
                                            <input id="radio_input_select" className="radio" type="checkbox" name="filter"/>
                                            <span className="radio_input"></span>
                                        </label>
                                    </div>
                                </td>
                            }
                            {this.props.ths.map((e,key) => {
                                return <td key={key}><a href="javascript:void(0)"><div className="item">{e}
                                    { typeof sort !== "function" ? null : <span><i className="fa fa-angle-up"></i><i className="fa fa-angle-down"></i></span>}
                                </div></a></td>
                            })}
                        </tr>
                        </thead>
                    </table>
                    </div>
                    <div className="data_wrap">
                    <table className="datatable">
                        <colgroup ref={(node) => this.colgroup = node}>
                            {
                                this.props.selectDisable ||  <col/>
                            }
                            {
                                this.props.ths.map((e,i) => {
                                    return <col key={i}/>
                                })
                            }
                        </colgroup>
                        <tbody ref={(node) => this.tbody=node } onClick={selectCourseWrap}>
                        {trs}
                        </tbody>
                    </table>
                    </div>
                </div>
                <div className="page_ctrl">
                    <div className="page_state">已选{selectedCourses.length}项，共{totalCount}项</div>
                    <div className="fr">
                        <div className="page_select"></div>
                        <div className="page_options">
                            <span className="page_text">每页显示
                                <select name="limit" id="limit" onChange={onLimitChange} defaultValue={"全部"}>
                                    <option value="10" >10</option>
                                    <option value="30">30</option>
                                    <option value="50">50</option>
                                    <option value="100">100</option>
                                    <option value="全部">全部</option>
                                </select>
                                行</span>
                            <a className="page_filter_elem first_page disable" href="javascript:void(0)" onClick={changePageWrap(1)}>
                                <i className="fa fa-angle-double-left"></i>
                            </a>
                            <a className="page_filter_elem prev_page disable" href="javascript:void(0)" onClick={changePageWrap(this.page - 1)}>
                                <i className="fa fa-angle-left"></i>
                            </a>
                            <a className="page_filter_elem" id="page">{this.page}</a>
                            <a className="page_filter_elem next_page" href="javascript:void(0)" onClick={changePageWrap(this.page + 1)}><i className="fa fa-angle-right"></i></a>
                            <a className="page_filter_elem last_page" href="javascript:void(0)" onClick={changePageWrap(totalCount % this.limit !== 0 ? parseInt(totalCount / this.limit) + 1 : totalCount / this.limit)}><i className="fa fa-angle-double-right"></i></a>
                        </div>
                    </div>
                </div>
            </div>
        )
    }
}

DataTable.propTypes = {
    refresh : PropTypes.func.isRequired,
    courses : PropTypes.array.isRequired,
    sort : PropTypes.func.isRequired,
    search : PropTypes.func.isRequired,
    ths : PropTypes.array,
    trs : PropTypes.array,
    addDisable : PropTypes.bool,
    editDisable : PropTypes.bool,
    selectDisable : PropTypes.bool,
    editHref : PropTypes.string,
    searchPlaceHolder : PropTypes.string,
    showModal : PropTypes.func
}

export default DataTable